View can get animated when some of its Properties change trough @State Variable like: Color, Position, Size, Rotation.
Change in @State Variable redraws the View and by default new Property values are instantly applied to the View.
This means that View will instantly change color, size or move to a new position.
But if animation is applied to the View this change will be gradual - you will see the View moving into the new position.
Animation takes initial and new Property Values (Key frames) and creates animation through interpolation.
Animation can be defined by using
● .animation Modifier (implicit animation)
Same Animation is applied every time the View is redrawn (when any State Variable changes)
● wrap changes to @State Variable inside a call to withAnimation() (explicit animation)
Different Animation can be applied for the same View (based on Animation specified for each call)
To trigger Animation we need to change some State Variable either inside
● Button action which is executed when Button is clicked
● .onAppear Modifier which is executed after adding View to Screen (drawn for the first time)
● .onTapGesture Modifier which is executed when you tap on the View
Difference between Animation and Transition is that
● Animation is performed when View Properties change and View gets redrawn
● Transition is performed when View is added or removed from the Hierarchy
.animation Modifier
Text("World")
.offset(x: offset)
.animation(Animation.easeOut(duration: 5))
.onAppear { self.offset = 100 }
withAnimation()
Text("World")
.offset(x: offset)
.onAppear { withAnimation(Animation.easeInOut(duration: 5)) { self.offset = 100 } }
Content
withAnimation()
.onAppear .onAppear { … }
Without Animation self.offset = 100
With Default Animation withAnimation() { self.offset = 100 }
With Custom Animation withAnimation(.easeInOut(duration: 5)) { self.offset = 100 }
Button action action: { … }
Without Animation self.offset = 100
With Default Animation withAnimation() { self.offset = 100 }
With Custom Animation withAnimation(.easeInOut(duration: 5)) { self.offset = 100 }
.animation
.onAppear
Button action